from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import QianfanEmbeddingsEndpoint
from docx import Document
from docx.shared import Pt
import re
import os
from difflib import SequenceMatcher
from langchain_community.embeddings import DashScopeEmbeddings

os.environ["QIANFAN_AK"]="SGbbQdjFjlKurTfUIjYM0Q4P"
os.environ["QIANFAN_SK"]="lb1tKvDGRhqLZYH4ZYpke6Vco9n9X8Xv"
def is_leaf_title(idx, lines, current_level):
    """判断当前标题是否为最后一级"""
    for i in range(idx + 1, len(lines)):
        line = lines[i]
        next_level = (len(line) - len(line.lstrip(" "))) // 2
        if next_level > current_level:
            return False
        elif next_level <= current_level:
            break
    return True
def doc_llm_generation(con):
    import os
    from openai import OpenAI
    os.environ["DASHSCOPE_API_KEY"] = "sk-5c6689dccd074a739c78ef7d1d780148"
    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
    )
    completion = client.chat.completions.create(
        model="deepseek-v3",
        messages=[
            {"role": "system", "content": '''
            你是一个写投标标书的小助手，根据user提供的content，完成以下的要求。
            第一content是段落内容，你需要将不同的段落整理成docx文件的格式，
            第二每个段落需要首行缩进俩个占位字符，段落之间要有空一行，
            第三你需要判断，第一个段落是不是完整的一个句子，或者完整的一个段落，如果不是，你需要根据上下文整理成完整的一句话，或者完整的一个段落。
            第四你需要判断，最后个段落是不是完整的一句话，或者完整的一个段落，如果不是完整的一个段落或者完整的一句话，你需要整理成一段话，或者完整的一个段落 。
            第五，如果有章节号，需要去掉。
            输出格式是docx文件的风格,禁止用markdown风格输出，除了上述要求，其他的不要修改，也不要做总结,
            '''},
            {"role": "user", "content": con},
        ],
    )
    return completion.choices[0].message.content
def search_doc_content(query):
    # embedding = QianfanEmbeddingsEndpoint()
    embeddings = DashScopeEmbeddings(
        model="text-embedding-v2",
        dashscope_api_key="sk-5c6689dccd074a739c78ef7d1d780148",
    )
    db = Chroma(persist_directory="D:\\hbyt\\project\\aibid\\db\\d1", embedding_function=embeddings)
    results = db.similarity_search(query, k=10)
    for i in results:
        print(i)
        print("++++++++++++++++++++++++")
        print("i.page_content:",i.page_content)
        print("i.metadata['source']",i.metadata["source"])
        print("i.id",i.metadata["id"])
        print("i.id", i.id)
        print("+++++++++++++++++++++++++")
    # for r in results:
    #     print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    #     print(r.page_content)
    # print("+++++++++++++++++++++++++++++++++++++")
    result = db.similarity_search_with_score(query, k=1)
    # print("相似的值：",result)
    for doc, score in result:
        similarity = 1 / (1 + score)  # 将距离转换为相似度（粗略处理）
        print("相似的值：",similarity)
        if similarity >0.5:
            # print(f"文档内容：{doc.page_content}")
            print(f"相似度（近似值）：{similarity:.4f}")
            # return results[0].page_content
    #     else:
    #         return doc_llm_generation(query)

    # similarity = SequenceMatcher(None, query, results[0].page_content).ratio()
    # print(similarity)
    # if similarity >0.9:
    #     print(similarity)
    #     return results[0].page_content
    # else:
    #      return doc_llm_generation(query)
    return  results

# def write_outline_to_docx(md_path, output_path):
#     print("ok")
#     doc = Document()
#     # doc.add_heading("目录结构文档", level=1)
#     with open(md_path, 'r', encoding='utf-8') as f:
#         lines = [line for line in f if line.strip().startswith("-")]
#     for idx, line in enumerate(lines):
#         level = (len(line) - len(line.lstrip(" "))) // 2
#         title = line.strip("- ").strip()
#         # 写标题（Word 标题1~6）
#         doc.add_heading(title, level=min(level + 1, 6))
#         # 如果是最后一级，写正文内容
#         if is_leaf_title(idx, lines, level):
#             # pars=doc_llm_generation(search_doc_content(re.sub(r'^\d+(\.\d+)*\s*', '', title)))
#             print("检索到的内容",search_doc_content(re.sub(r'^\d+(\.\d+)*\s*', '', title)))
#             para=doc.add_paragraph("内容来源路径source:"+search_doc_content(re.sub(r'^\d+(\.\d+)*\s*', '', title))[0].metadata["source"])
#             para = doc.add_paragraph(search_doc_content(re.sub(r'^\d+(\.\d+)*\s*', '', title))[0].page_content)
#             # para = doc.add_paragraph(search_doc_content(re.sub(r'^\d+(\.\d+)*\s*', '', title)))
#             para.style.font.size = Pt(10)
#             para.paragraph_format.first_line_indent = Pt(24)  # 24pt = 2 字符（大约）
#     doc.save(output_path)
# # 用法示例
# write_outline_to_docx("D:\\hbyt\\AI智能投标\\典型招标要求和投标文件\\典型投标标书目录\\投标文件-技术部分-天翼视联6.12终版.md", "投标文件.docx")

if __name__ == '__main__':
    print(search_doc_content("一.1.1EHS保障体系-管理策略和落实")[0].page_content)
    # print(search_doc_content("慧博云通的薪酬与福利体系遵循PPP原则")[0].page_content)
